package com.cloud.edu.subject.service.impl;

import com.cloud.edu.bus.entity.SubjectEntity;
import com.cloud.edu.subject.dao.UserQuestionsKnowMapper;
import com.cloud.edu.subject.dao.UserQuestionsMapper;
import com.cloud.edu.subject.model.UserQuestions;
import com.cloud.edu.subject.model.UserQuestionsKnow;
import com.cloud.edu.subject.service.UserQuestionsService;
import com.cloud.edu.sys.dao.SqlAdapterMapper;
import com.cloud.edu.utils.PageUtils;
import com.cloud.edu.utils.UuidUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("userQuestionsService")
public class UserQuestionsServiceImpl  implements UserQuestionsService {
	
	@Autowired
	private UserQuestionsMapper userQuestionsMapper;
	
	@Autowired
	private UserQuestionsKnowMapper userQuestionsKnowMapper;
	
	@Autowired
   	private SqlAdapterMapper sqlAdapterMapper;//注入dao
	
	@Autowired
    private MongoTemplate mongoTemplate;


	/**
	 * 分页查询
	 */
	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		PageUtils pageUtils=PageUtils.getPageInfo(params);
		Page<Object> p = PageHelper.startPage(pageUtils.getPage(), pageUtils.getLimit());
		StringBuffer sql=new StringBuffer(" SELECT S.`ID`,(SELECT T.DATA_NAME FROM SYS_DICTIONARY T WHERE T.DATA_CODE=S.`SBJ`) SBJNAME,(SELECT T.DATA_NAME FROM SYS_DICTIONARY T WHERE T.DATA_CODE=S.`TYPE`) TYPENAME,S.`REMARK`,S.`STATE`,DATE_FORMAT(CREATE_TIME, '%Y-%m-%d %H:%i:%s') CREATE_TIME FROM BUS_USER_QUESTIONS S ORDER BY CREATE_TIME DESC ");
		sqlAdapterMapper.selectSQL(sql.toString());
		pageUtils =new PageUtils(p);
		return pageUtils;
	}
	
	/**
	 * 保存信息
	 */
	@Override
	public void save(UserQuestions UserQuestions) {
		UserQuestions.setId(UuidUtil.get32UUID());
		UserQuestions.setCreateTime(new Date());
		userQuestionsMapper.insert(UserQuestions);
	}
	
	/**
	 * 保存题目信息
	 */
	@Override
	public void saveQue(JSONObject obj) throws Exception{
		
		String sbj=obj.getString("sbj");
		String type=obj.getString("type");
		String remark=obj.getString("remark");
		String rightKey=obj.getString("rightKey");
		if(obj.containsKey("rightKeyData")){
			String rightKeyData=obj.getString("rightKeyData");
			if("100103".equals(type)){
				rightKey=rightKeyData;
			}
		}
		UserQuestions userQuestions=new UserQuestions();  //题目信息
		userQuestions.setSbj(sbj);
		userQuestions.setType(type);
		userQuestions.setRemark(remark);
		this.save(userQuestions);//保存题目信息
		
		if(obj.containsKey("knows")){//题目知识点关联
			if(obj.get("knows")!=null&&!("").equals(obj.get("knows"))){
				JSONArray knowsArray=(JSONArray) obj.get("knows");
				for(int i=0;i<knowsArray.size();i++){
					JSONObject jobj=(JSONObject) knowsArray.get(i);
					String knowId=jobj.getString("id");
					UserQuestionsKnow record=new UserQuestionsKnow();
					record.setId(UuidUtil.get32UUID());
					record.setQuesId(userQuestions.getId());
					record.setKnowId(knowId);
					userQuestionsKnowMapper.insert(record);
				}
			}
		}
		//题目明细信息
		SubjectEntity subjectEntity=new SubjectEntity();
		subjectEntity.setSubId(userQuestions.getId());
		subjectEntity.setTitle(remark);
		subjectEntity.setRightKey(rightKey);
		if(obj.containsKey("options")){//选项信息
			if(obj.get("options")!=null&&!("").equals(obj.get("options"))){
				JSONArray optionsArray=(JSONArray) obj.get("options");
				subjectEntity.setOptions(optionsArray.toString());
			}
		}
		mongoTemplate.save(subjectEntity);
		
//		UserQuestions.setId(UuidUtil.get32UUID());
//		userQuestionsMapper.insert(UserQuestions);
//		UserQuestions userQuestions=
	}

	/**
	 * 更新题目
	 * @param params
	 * @throws Exception
	 */
	public void updateQue(JSONObject obj) throws Exception{

		String id=obj.getString("id");
		String sbj=obj.getString("sbj");
		String type=obj.getString("type");
		String remark=obj.getString("remark");
		String rightKey=obj.getString("rightKey");
		if(obj.containsKey("rightKeyData")){
			String rightKeyData=obj.getString("rightKeyData");
			if("100103".equals(type)){
				rightKey=rightKeyData;
			}
		}
		UserQuestions userQuestions=this.selectById(id);  //题目信息
//		userQuestions.setSbj(sbj);
//		userQuestions.setType(type);
		userQuestions.setRemark(remark);
		this.update(userQuestions);//更新题目信息
		
		//删除原有知识点关联
		StringBuffer sql=new StringBuffer("delete FROM `bus_user_questions_know` WHERE QUES_ID='"+id+"'");
		sqlAdapterMapper.deleteSQL(sql.toString());
		//题目知识点关联
		if(obj.containsKey("knows")){
			if(obj.get("knows")!=null&&!("").equals(obj.get("knows"))){
				JSONArray knowsArray=(JSONArray) obj.get("knows");
				for(int i=0;i<knowsArray.size();i++){
					JSONObject jobj=(JSONObject) knowsArray.get(i);
					String knowId=jobj.getString("id");
					UserQuestionsKnow record=new UserQuestionsKnow();
					record.setId(UuidUtil.get32UUID());
					record.setQuesId(userQuestions.getId());
					record.setKnowId(knowId);
					userQuestionsKnowMapper.insert(record);
				}
			}
		}
		
		//删除原有题目
		Query query = Query.query(Criteria.where("subId").is(id));
		mongoTemplate.remove(query,SubjectEntity.class);
		//题目明细信息
		SubjectEntity subjectEntity=new SubjectEntity();
		subjectEntity.setSubId(userQuestions.getId());
		subjectEntity.setTitle(remark);
		subjectEntity.setRightKey(rightKey);
		if(obj.containsKey("options")){//选项信息
			if(obj.get("options")!=null&&!("").equals(obj.get("options"))){
				JSONArray optionsArray=(JSONArray) obj.get("options");
				subjectEntity.setOptions(optionsArray.toString());
			}
		}
		mongoTemplate.save(subjectEntity);
	}
	
	
	/**
	 * 获取问题信息
	 */
	public JSONObject getQueById(String id) throws Exception{
		JSONObject obj=new JSONObject();
		UserQuestions userQuestions=userQuestionsMapper.selectByPrimaryKey(id);
		
		StringBuffer sql=new StringBuffer("SELECT s.`ID`,s.`NAME` FROM `bus_knows` s,`bus_user_questions_know` w WHERE w.`KNOW_ID`=s.`ID` AND w.`QUES_ID`='"+id+"'");
//		
		List<Map<String, Object>> list=sqlAdapterMapper.selectSQL(sql.toString());
		
		
	    Query query = new Query();
        Criteria criteria = Criteria.where("subId").is(id);
        query.addCriteria(criteria);
        SubjectEntity subjectEntity=mongoTemplate.findOne(query, SubjectEntity.class);
        obj.put("que", userQuestions);
        obj.put("subjectEntity", subjectEntity);
        if(list!=null&&list.size()>0){
        	 obj.put("knows", list);
		}
		return obj;
	}

	/**
	 * 知识点分页查询
	 */
	@Override
	public PageUtils queryKnowsPage(Map<String, Object> params) {
		PageUtils pageUtils=PageUtils.getPageInfo(params);
		Page<Object> p = PageHelper.startPage(pageUtils.getPage(), pageUtils.getLimit());
		StringBuffer sql=new StringBuffer(" SELECT S.`ID`,S.NAME,S.`REMARK`,S.`STATE`,DATE_FORMAT(CREATE_TIME, '%Y-%m-%d %H:%i:%s') CREATE_TIME FROM BUS_KNOWS S ORDER BY CREATE_TIME DESC ");
		sqlAdapterMapper.selectSQL(sql.toString());
		pageUtils =new PageUtils(p);
		return pageUtils;
	}
	
	/**
	 * 更新信息
	 */
	@Override
	public void update(UserQuestions UserQuestions) {
		userQuestionsMapper.updateByPrimaryKey(UserQuestions);
	}

	/**
	 * 删除信息
	 */
	@Override
	public void deleteBatch(String[] ids) {
		for(String id:ids){
			//删除题干
			userQuestionsMapper.deleteByPrimaryKey(id);
			
			//删除原有知识点关联
			StringBuffer sql=new StringBuffer("delete FROM `bus_user_questions_know` WHERE QUES_ID='"+id+"'");
			sqlAdapterMapper.deleteSQL(sql.toString());
			
			//删除原有题目
			Query query = Query.query(Criteria.where("subId").is(id));
			mongoTemplate.remove(query,SubjectEntity.class);
		}
		
	}
	
	/**
	 * 主键获取信息
	 */
	public UserQuestions selectById(String id) throws Exception{
		UserQuestions userQuestions=userQuestionsMapper.selectByPrimaryKey(id);
		return userQuestions;
	}
}
